#include "filebrowse.h"

extern u8 font_ttf[];
extern u32 font_ttf_size;

extern u8 browseBg_png[];
extern u8 cube_load_png[];
extern u8 cube_load_score_png[];

FileBrowse::FileBrowse(HighScores* scr)
{
	_cubeFile = new Image();
	_cubeScore = new Image();
	
	_ptrHighScores = scr;
	
   if(_cubeFile->LoadImage(cube_load_png, IMG_LOAD_TYPE_BUFFER)!= IMG_LOAD_ERROR_NONE)exit(0);
   if(_cubeScore->LoadImage(cube_load_score_png, IMG_LOAD_TYPE_BUFFER)!= IMG_LOAD_ERROR_NONE)exit(0);
   
	_selectedIndex = 0;
	PopulateList();
	
	_textImage = new DrawableImage();
	_textImage2 = new DrawableImage();
	_textRender = new TextRender();

    _textRender->SetFont(font_ttf, font_ttf_size);

	_textImage->CreateImage(640, 128);
	_textImage->SetFont(_textRender);
	_textImage->SetColor((GXColor){0,0,0,255});
	_textImage->SetSize(16);
	
	_textImage2->CreateImage(640, 128);
	_textImage2->SetFont(_textRender);
	_textImage2->SetColor((GXColor){0,0,0,255});
	_textImage2->SetSize(16);
    
	_bgSprite.SetImage(_cubeFile);
	_bgSprite.SetPosition(0, -30);
	
	_cancel = false;
}

FileBrowse::~FileBrowse()
{

}

void FileBrowse::ClearIndex()
{
	_selectedIndex = 0;
    _scroll = 0;
    _start_scroll = 10;
}
	
void FileBrowse::PopulateList()
{
	_cancel = false;
	
	_fileList.clear();

	char* url = (char*)"sd://apps/portii/";

	// Ensure settings back to defaults
	
	// Temporary data for directory list
	char fileName[MAXPATHLEN];
	FileType fileType;
	
        // Open directory
        File dir;
        dir.open(url, "d");
        
        // Loop through and add all
        while(dir.findNextFile(fileName, fileType))
        {
                if(strcmp(fileName, ".") == 0) { continue; }
        
                
                if(fileType != FILE_DIRECTORY)
                {
                        // Figure out if it's supported or not
                        if(strlen(fileName)>7)
                        {
                                if(fileName[strlen(fileName) - 7] == '.' &&
                                        fileName[strlen(fileName) - 6] == 'p' &&
                                        fileName[strlen(fileName) - 5] == 'o' &&
                                        fileName[strlen(fileName) - 4] == 'r' &&
                                        fileName[strlen(fileName) - 3] == 't' &&
                                        fileName[strlen(fileName) - 2] == 'i' &&
                                        fileName[strlen(fileName) - 1] == 'i')
                                {
                                        _fileList.push_back(std::string(fileName));
                                }
                                
                        }
                }
                
        }
		
        // No leaked handles please
        dir.close();
		
}

void FileBrowse::InsertFront(char* lvl)
{

    _fileList.insert(_fileList.begin(), std::string(lvl));
}

bool FileBrowse::Update(Pointer* ptr, GameMode::Type gm)
{
	
	if(gm == GameMode::STORY)
		_bgSprite.SetImage(_cubeFile);
	else
		_bgSprite.SetImage(_cubeScore);
	
	
	WPAD_ScanPads();
	
	u16 btnsdown = WPAD_ButtonsDown(0);

	if(btnsdown & WPAD_BUTTON_A)
	{
		return false;
	}
	
	if(btnsdown & WPAD_BUTTON_DOWN)
	{
		if(_selectedIndex < (int)_fileList.size()-1)
		{
			_selectedIndex++;
		}
		
		if(_selectedIndex > _start_scroll && _scroll < ((int)_fileList.size() - _start_scroll))
			_scroll++;
	}
	
	if(btnsdown & WPAD_BUTTON_UP)
	{
		if(_selectedIndex > 0)
		{
			_selectedIndex--;
		}
		
		if(_selectedIndex < _start_scroll && _scroll > 0)
			_scroll--;
	}
	
	if(btnsdown & WPAD_BUTTON_B || btnsdown & WPAD_BUTTON_HOME)
	{
		_cancel = true;
		return false;
	}
	
	
	Render(gm);
	
	return true;
}
		
void FileBrowse::Render(GameMode::Type gm)
{
   bool swap = false;

   Quad selQuad;
   		
   selQuad.SetWidth(315);
   selQuad.SetHeight(30);
   selQuad.SetPosition(30,50);
   
   selQuad.SetFillColor((GXColor){ 112, 203, 255, 200 });
   
	_bgSprite.Draw();
	
	int num_drawn = 0;
	
	if(_fileList.size() > 0)
	{
		//Draw list
		for(int i = _scroll; i < ((int)_fileList.size()) && i < _scroll + _start_scroll +1; i++)
		{
				if(_selectedIndex == i)
				{
					selQuad.SetPosition(35, 50+num_drawn*30);
					selQuad.Draw();
				}
				
				if(swap)
				{
					switch(gm)
					{
						case GameMode::STORY:
							_textImage->RenderText(_fileList[i].c_str());
							_textSprite.SetImage(_textImage->GetImage());
							swap = false;
							break;
						case GameMode::TIMED:
							{
								char buff[200];
								
								double elapsed = _ptrHighScores->GetHighScore(gm, (char*)_fileList[i].c_str());
								
								char timestr[40];
								int rem;
								
								if(elapsed != UNDEFINED_SCORE)
								{
									
									struct tm mytm;
									mytm.tm_sec = (int)(elapsed/1000.0)%60;
									mytm.tm_min = (elapsed/1000.0)/60.0;
									
									
									rem = ((elapsed - ((mytm.tm_sec)*1000) - ((mytm.tm_min)*60000))/1000)*100;
									
									strftime(timestr, sizeof(timestr), "%M:%S", &mytm);
									int k = strlen(_fileList[i].c_str());
									k=25-k;
									sprintf(buff, "%s%*s%s:%02d", _fileList[i].c_str(), k," ", timestr, rem);
								}
								else
								{
									sprintf(timestr, "---");
									int k = strlen(_fileList[i].c_str());
									k=25-k;
									sprintf(buff, "%s%*s%s", _fileList[i].c_str(), k," ", timestr);

								}
								
								_textImage->RenderText(buff);
								_textSprite.SetImage(_textImage->GetImage());
								swap = false;
							}
							break;
						case GameMode::PORTAL_COUNT:
							{
								int k = strlen(_fileList[i].c_str());
								k=25-k;
								char buff[200];
								int score = _ptrHighScores->GetHighScore(gm, (char*)_fileList[i].c_str());
								
								if(score != UNDEFINED_SCORE)
								{
									sprintf(buff, "%s%*s%d", _fileList[i].c_str(), k," ", score);
								}
								else
								{
									sprintf(buff, "%s%*s%s", _fileList[i].c_str(), k," ", "---");
								}								_textImage->RenderText(buff);
								_textSprite.SetImage(_textImage->GetImage());
								swap = false;
							}
							break;
						default:
							break;
					}
				}
				else
				{
					switch(gm)
					{
						case GameMode::STORY:
							_textImage2->RenderText(_fileList[i].c_str());
							_textSprite.SetImage(_textImage2->GetImage());
							swap = true;
							break;
						case GameMode::TIMED:
							{
								char buff[200];
								
								double elapsed = _ptrHighScores->GetHighScore(gm, (char*)_fileList[i].c_str());
								int rem;
								char timestr[40];
								
								if(elapsed != UNDEFINED_SCORE)
								{
									
									struct tm mytm;
									mytm.tm_sec = (int)(elapsed/1000.0)%60;
									mytm.tm_min = (elapsed/1000.0)/60.0;
									
									
									rem = ((elapsed - ((mytm.tm_sec)*1000) - ((mytm.tm_min)*60000))/1000)*100;
									
									strftime(timestr, sizeof(timestr), "%M:%S", &mytm);
									int k = strlen(_fileList[i].c_str());
									k=25-k;
									sprintf(buff, "%s%*s%s:%02d", _fileList[i].c_str(), k," ", timestr, rem);
								}
								else
								{
									sprintf(timestr, "---");
									int k = strlen(_fileList[i].c_str());
									k=25-k;
									sprintf(buff, "%s%*s%s", _fileList[i].c_str(), k," ", "---");

								}
								
								_textImage2->RenderText(buff);
								_textSprite.SetImage(_textImage2->GetImage());
								swap = true;
							}
							break;
						case GameMode::PORTAL_COUNT:
							{
								char buff[200];
								int k = strlen(_fileList[i].c_str());
								k=25-k;
								int score = _ptrHighScores->GetHighScore(gm, (char*)_fileList[i].c_str());
								
								if(score != UNDEFINED_SCORE)
								{
									sprintf(buff, "%s%*s%d", _fileList[i].c_str(), k," ", score);
								}
								else
								{
									sprintf(buff, "%s%*s%s", _fileList[i].c_str(), k," ", "---");
								}
								
								_textImage2->RenderText(buff);
								_textSprite.SetImage(_textImage2->GetImage());
								swap = true;
							}
							break;
						default:
							break;
					}
				}

				_textSprite.SetPosition(40, 50+num_drawn*30);
				_textSprite.Draw();
				
				num_drawn++;
		}
	}
	else
	{
		_cancel = true;
		
		_textImage->RenderText("No portii Files available.");
		_textSprite.SetImage(_textImage->GetImage());
		_textSprite.SetPosition(40,50);
		_textSprite.Draw();
	}
	
}
		
char* FileBrowse::GetSelectedFile()
{
	if((int)_fileList.size() > _selectedIndex)
	{
		return (char*)_fileList[_selectedIndex].c_str();
	}
	else
	{
		return NULL;
	}
}
	
int FileBrowse::GetSelectedFileIndex()
{
	if((int)_fileList.size() > _selectedIndex)
	{
		return _selectedIndex;
	}
	
	return -1;
}
